package com.mmp.main.servlet.device;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.common.util.Common;
import com.mmp.common.util.FileUtil;
import com.mmp.main.entity.HospitalDepartment;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.HospitalDeviceAccessory;
import com.mmp.main.entity.LookupDeviceCategory;
import com.mmp.main.entity.User;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

@MultipartConfig
public class DeviceInfoProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		User sessionUser = getSessionUser(request);
		Date now = new Date();

		int deviceId = WebUtil.getParamValueAsInteger(request, "deviceId", 0);
		HospitalDevice device = null;

		if (deviceId != 0) { // update mode
			device = dbQueryManager.findById(deviceId, HospitalDevice.class);
			device.setLastModifiedBy(sessionUser);
			device.setLastModifiedIn(now);
		} else { // entry mode
			device = new HospitalDevice();
			device.setStatus(Enums.DEVICE_STATUS.WORK_PROPERLY.getStatus());
			device.setSite(getSessionUser(request).getSite());
			device.setHospital(getSessionLocation(request));
			device.setCreatedBy(sessionUser);
			device.setCreatedIn(now);
		}

		device.setCode(WebUtil.getParamValue(request, "code", null));
		device.setSerialNo(WebUtil.getParamValue(request, "serial", null));
		device.setName(WebUtil.getParamValue(request, "name", null));
		device.setManufacturerName(WebUtil.getParamValue(request, "manufacturerName", null));
		device.setModel(WebUtil.getParamValue(request, "model", null));

		int category = WebUtil.getParamValueAsInteger(request, "category", 0);
		if (category != 0) {
			LookupDeviceCategory categoryObj = new LookupDeviceCategory();
			categoryObj.setId(category);
			device.setCategory(categoryObj);
		}

		device.setAgentName(WebUtil.getParamValue(request, "agentName", null));

		device.setSubcontractor(WebUtil.getParamValue(request, "subcontractor", null));

		int dep = WebUtil.getParamValueAsInteger(request, "dep", 0);
		if (dep != 0) {
			HospitalDepartment depObj = new HospitalDepartment();
			depObj.setId(dep);
			device.setHospitalDepartment(depObj);
		}

		device.setOperationDate(WebUtil.getParamValueAsDate(request, "operationDate", null));
		device.setTa3midNo(WebUtil.getParamValue(request, "ta3midNo", null));
		device.setPrice(WebUtil.getParamValueAsFloat(request, "price", null));

		String[] otherAttachments = FileUtil.uploadFiles(request, "otherAttachments");
		// if (otherAttachments != null && otherAttachments.length != 0)
		device.setOtherAttachments(Common.concatenateValues(otherAttachments));

		// reset values
		device.setWithinWarranty(false);
		device.setWarrantyExpireDate(null);
		device.setWithinContract(false);
		device.setAddedFromAnotherLocation(false);
		device.setLocationName(null);
		device.setAddDate(null);

		String withinWarranty = WebUtil.getParamValue(request, "withinWarranty", null);
		if (withinWarranty != null)
			device.setWithinWarranty("1".equals(withinWarranty) ? true : false);

		if (device.getWithinWarranty() != null && device.getWithinWarranty() == true) {
			device.setWarrantyExpireDate(WebUtil.getParamValueAsDate(request, "warrantyExpireDate", null));
			// added in 01/06/2015
			if (category == Enums.DEVICE_CATEGORY.C.getDBId())
				device.setWithinContract(true);

		} else {
			String withinContract = WebUtil.getParamValue(request, "withinContract", null);
			if (withinContract != null)
				device.setWithinContract("1".equals(withinContract) ? true : false);

			if (device.getWithinContract() != null && device.getWithinContract() == false) {

				String addedFromAnotherLocation = WebUtil.getParamValue(request, "addedFromAnotherLocation", null);
				if (addedFromAnotherLocation != null)
					device.setAddedFromAnotherLocation("1".equals(addedFromAnotherLocation) ? true : false);

				if (device.getAddedFromAnotherLocation() != null && device.getAddedFromAnotherLocation() == true) {
					device.setLocationName(WebUtil.getParamValue(request, "locationName", null));
					device.setAddDate(WebUtil.getParamValueAsDate(request, "addDate", null));

				}
			}
		}

		device.setPmAnnualVisitsNo(WebUtil.getParamValueAsInteger(request, "pmAnnualVisitsNo", null));

		String[] pmVisitsMonths = request.getParameterValues("pmVisitsMonths");
		if (pmVisitsMonths != null && pmVisitsMonths.length != 0)
			device.setPmVisitsMonths(Common.concatenateValues(pmVisitsMonths));

		if (device.getHospitalDeviceAccessories() == null)
			device.setHospitalDeviceAccessories(new ArrayList<HospitalDeviceAccessory>());
		else
			device.getHospitalDeviceAccessories().clear();

		String deviceAccessories_rowOrder = request.getParameter("deviceAccessories_rowOrder");
		if (deviceAccessories_rowOrder != null && !deviceAccessories_rowOrder.isEmpty()) {

			String[] indexes = deviceAccessories_rowOrder.split(",");
			for (int i = 0; i < indexes.length; i++) {
				HospitalDeviceAccessory acc = new HospitalDeviceAccessory();
				acc.setQuantity(WebUtil.getParamValueAsInteger(request, "deviceAccessories_accQuantity_" + indexes[i],
						null));
				acc.setDescription(WebUtil.getParamValue(request, "deviceAccessories_accDescription_" + indexes[i],
						null));
				device.addHospitalDeviceAccessory(acc);
			}
		}

		device = dbQueryManager.mergeEntity(device);

		if (deviceId == 0) {
			setMessage(request, new Message("تمت  إضافة الجهاز بنجاح", Message.MESSAGE_TYPE.SUCCESS));
			sendRedirect(request, response, "DeviceInfoDisplay");

		} else {
			setMessage(request, new Message("تم تعديل بيانات الجهاز بنجاح", Message.MESSAGE_TYPE.SUCCESS));
			sendRedirect(request, response, "UpdateDeviceInfoSearch");
		}
	}
}
